import Taro, { useLoad } from '@tarojs/taro';
import { Input, Text, View } from '@tarojs/components';
import { Button, Cell, GroupList, Header, ScrollView, Space, TopView } from 'pd-taro-ui';
import { PageParams } from './route.config';
import { useRouterData } from '@/utils/router';
import { FormikHelpers, FormikProps } from 'formik';
import { useRef, useState } from 'react';
import { string, object, array } from 'yup';
import { Form, FormItem } from 'pd-taro-form';
import { usePcaList } from '@/utils/city';
import { inputNumberPercentProps, inputNumberPercentilesProps } from 'pd-taro-form/InputNumber/utils';
import type { FormProps } from 'pd-taro-form/Form';
import './index.scss';
import { RequestResponse } from '@/utils/request/type';
import { asyncTimeOut, flatFormikErrors } from '@/utils/util';

const prefix = 'TODODemoFormPage__';
interface MyFormValues {
  email: string;
  text: string;
  bool: boolean;
  checks: string[];
  radio: string;
  select: string;
  selects: string;
  tree: string;
  trees: string[];
  startDate: string;
  dates: string;
  picker: string;
  pickers: string;
  timePicker: string;
  dateTimePicker: string;
  timeDayPicker: string;
  cascader: string;
  cascaders: string;
  num: number;
}

const options = [
  {
    label: 'A',
    value: 'a',
    children: [
      {
        label: 'A1',
        value: 'a1',
      },
      {
        label: 'A2',
        children: [
          {
            label: 'A21',
            value: 'a21',
          },
          {
            label: 'A22',
            value: 'a22',
          },
        ],
      },
    ],
  },
  { label: 'B', value: 'b', disabled: true },
  {
    label: 'C',
    value: 'c',
    children: [
      {
        label: 'C1',
        value: 'c1',
      },
      {
        label: 'C2',
        value: 'c2',
      },
    ],
  },
];

const cascaderOptions = [
  {
    label: 'A',
    value: 'a',
    children: [
      {
        label: 'A1',
        value: 'a1',
      },
      {
        label: 'A2',
        value: 'a2',
        children: [
          {
            label: 'A22',
            value: 'a22',
          },
          {
            label: 'A21',
            value: 'a21',
            children: [
              {
                label: 'A31',
                value: 'a31',
                children: [
                  {
                    label: 'A41',
                    value: 'a41',
                    children: [
                      {
                        label: 'A51',
                        value: 'a51',
                        children: [
                          {
                            label: 'A61',
                            value: 'a61',
                          },
                        ],
                      },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
  { label: 'B', value: 'b', disabled: true },
  {
    label: 'C',
    value: 'c',
    children: [
      {
        label: 'C1',
        value: 'c1',
      },
      {
        label: 'C2',
        value: 'c2',
      },
    ],
  },
];
const FormPage = () => {
  const router = useRouterData();

  const [staticed, setStaticed] = useState(false);
  const [disabled, setDisabled] = useState<boolean | undefined>(undefined);
  const [direction, setDirection] = useState<FormProps['direction']>('horizontal');

  const [deferOptions, setDeferOptions] = useState<any[]>([]);

  const initialValues: Partial<MyFormValues> = {
    email: '1',
    text: '6666\n777',
    bool: false,
    checks: ['b'],
    radio: '1',
    select: '',
    selects: 'a,b',
    tree: '',
    startDate: '2020-01-01 10:11:12',
    files: [],
    files1: 'http://w.a.com/123456789123456789123456789123456789.png,http://w.a.com/2.png',
  };
  const formikRef = useRef<FormikProps<MyFormValues>>(null);

  const onSubmit = async (values: MyFormValues, formikHelpers: FormikHelpers<MyFormValues>) => {
    console.log('onSubmit', values);
    Taro.showLoading({ title: '提交中..', mask: true });
    formikHelpers.setSubmitting(true);
    setTimeout(() => {
      formikHelpers.setSubmitting(false);
      Taro.showToast({ icon: 'success', title: '提交成功' });
    }, 2000);
  };

  const pcaList = usePcaList();

  return (
    <TopView>
      <Header title='表单页demo' titleCenter />
      <ScrollView>
        <View style={{ fontSize: 24, marginBottom: 16 }}></View>
        <GroupList>
          <GroupList.Item title='表单'>
            <Cell title='大部分组件支持数据类型为：数组或字符串间隔' subTitle='使用joinValues:true ' />
            <Cell
              title='静态，以表单子项的为主'
              subTitle={`formStaticed: ${JSON.stringify(staticed)}`}
              desc={<Button onClick={() => setStaticed(!staticed)}>切换</Button>}
            />
            <Cell
              title='禁用，如果设置form这个，全部子项同步'
              subTitle={`disabled: ${JSON.stringify(disabled)}`}
              desc={
                <Space>
                  <Button onClick={() => setDisabled(!disabled)}>切换</Button>
                  <Button onClick={() => setDisabled(undefined)}>清空</Button>
                </Space>
              }
            />
            <Cell
              title='方向'
              subTitle={`direction: ${JSON.stringify(direction)}`}
              desc={<Button onClick={() => setDirection(old => (old === 'vertical' ? 'horizontal' : 'vertical'))}>切换</Button>}
            />
          </GroupList.Item>
        </GroupList>

        <Form
          innerRef={formikRef}
          validationSchema={object({
            email: string().nullable().required('email不能为空'),
          })}
          initialValues={initialValues}
          onSubmit={onSubmit}
          debug
          staticed={staticed}
          disabled={disabled}
          labelWidth={240}
          direction={direction}>
          {({ errors, values, handleChange, submitForm, isValid }) => {
            return (
              <View style={{ padding: 12 }}>
                <FormItem type='Switch' label='Switch是否' name='bool' placeholder='请输入' />

                <FormItem type='Input' label='文本框' name='email' placeholder='请输入' required clearable />
                <FormItem
                  type='Input'
                  label='文本框前后缀'
                  name='text2'
                  placeholder='请输入'
                  required
                  clearable
                  renderPrefix='$'
                  renderSuffix='元'
                />
                <FormItem
                  type='Input'
                  label='密码'
                  name='password'
                  placeholder='请输入'
                  required
                  clearable
                  compProps={{ type: 'safe-password', password: true }}
                />
                <FormItem type='InputNumber' label='数字' name='num' placeholder='请输入' required clearable />
                <FormItem type='InputNumber' label='数字小数点2' name='num2' placeholder='请输入' required clearable precision={2} />
                <FormItem
                  type='InputNumber'
                  label='数字-千分位'
                  name='num3'
                  placeholder='请输入'
                  required
                  clearable
                  precision={3}
                  {...inputNumberPercentilesProps}
                />
                <FormItem
                  type='InputNumber'
                  label='数字大小限制'
                  name='num4'
                  placeholder='请输入'
                  required
                  clearable
                  precision={2}
                  min={0}
                  max={9.99}
                />
                <FormItem
                  type='InputNumber'
                  label='数字百分比'
                  name='num5'
                  placeholder='请输入'
                  required
                  clearable
                  precision={4}
                  min={0}
                  max={1}
                  {...inputNumberPercentProps}
                  renderExtra='录入0.1, 显示10%'
                />
                <FormItem
                  type='Textarea'
                  label='Textarea多行输入'
                  name='text'
                  placeholder='请输入'
                  required
                  showCounter
                  maxlength={30}
                  compProps={{ autoHeight: true }}
                />

                <FormItem
                  type='CheckboxGroup'
                  label='CheckboxGroup多选'
                  name='checks'
                  placeholder='请输入'
                  required
                  joinValues={false}
                  options={[
                    { label: 'A', value: '1' },
                    { label: 'B', value: '2' },
                  ]}
                  inline={true}
                />
                <FormItem
                  type='RadioGroup'
                  label='RadioGroup单选'
                  name='radio'
                  placeholder='请输入'
                  required
                  options={[
                    { label: 'A', value: '1' },
                    { label: 'B', value: '2' },
                  ]}
                  inline={true}
                />
                <FormItem
                  type='Select'
                  label='Select单选'
                  name='select'
                  placeholder='请选择'
                  required
                  options={options}
                  inline={true}
                  clearable
                  searchable
                />
                <FormItem
                  type='Select'
                  label='Select多选'
                  name='selects'
                  placeholder='请选择'
                  required
                  options={options}
                  inline={true}
                  clearable
                  searchable
                  multiple={true}
                />
                <FormItem
                  type='Select'
                  label='Select树单选'
                  name='tree'
                  placeholder='请选择'
                  required
                  options={options}
                  inline={true}
                  clearable
                  searchable
                  selectMode='tree'
                />
                <FormItem
                  type='Select'
                  label='Select树多选'
                  name='trees'
                  placeholder='请选择'
                  required
                  options={options}
                  inline={true}
                  clearable
                  searchable
                  selectMode='tree'
                  joinValues={false}
                  multiple={true}
                />
                <FormItem
                  type='Select'
                  label='Select树异步查询'
                  name='treeDefer'
                  placeholder='请选择'
                  required
                  inline={true}
                  clearable
                  searchable
                  selectMode='tree'
                  options={deferOptions}
                  onChangeOptions={setDeferOptions}
                  deferApi={async item => {
                    await asyncTimeOut(500).then(() => {});
                    if (!item) return [{ label: '1', value: '1' }];
                    return [
                      { label: item.label + '-1', value: item.value + '-1' },
                      { label: item.label + '-2', value: item.value + '-2', disabledExpand: true },
                      { label: item.label + '-3', value: item.value + '-3', disabledCheck: true },
                    ];
                  }}
                />
                <FormItem
                  type='DateInput'
                  label='日期选择'
                  name='startDate'
                  placeholder='请选择'
                  required
                  clearable
                  mode='day'
                  minDate='2022-01-01'
                />
                <FormItem type='DateInput' label='日期范围' name='dates' placeholder='请选择' required clearable mode='range' showTime />
                <FormItem
                  type='Picker'
                  mode='selector'
                  label='Picker单个'
                  name='picker'
                  options={options}
                  placeholder='请选择'
                  required
                  clearable
                />
                <FormItem
                  type='Picker'
                  mode='multiSelector'
                  label='Picker多列'
                  name='pickers'
                  options={[options, options]}
                  placeholder='请选择'
                  required
                  clearable
                  joinValues={false}
                />
                <FormItem
                  type='TimePicker'
                  label='TimePicker-time'
                  timeRange='time'
                  name='timePicker'
                  placeholder='请选择'
                  required
                  clearable
                />
                <FormItem
                  type='TimePicker'
                  label='TimePicker-day'
                  timeRange='day'
                  name='timeDayPicker'
                  placeholder='请选择'
                  required
                  clearable
                />
                <FormItem
                  type='TimePicker'
                  label='TimePicker-day-time'
                  timeRange='day-time'
                  name='dateTimePicker'
                  placeholder='请选择'
                  required
                  clearable
                />
                <FormItem
                  type='Cascader'
                  label='Cascader-单选'
                  name='cascader'
                  placeholder='请选择'
                  required
                  clearable
                  options={cascaderOptions}
                />
                <FormItem
                  type='Cascader'
                  label='Cascader-多选'
                  name='cascaders'
                  placeholder='请选择'
                  required
                  clearable
                  options={cascaderOptions}
                  multiple
                  onlyLeaf={false}
                />
                <FormItem
                  type='Cascader'
                  label='Cascader-省市区'
                  name='pcas'
                  placeholder='请选择'
                  required
                  clearable
                  options={pcaList}
                  onChange={(value, items) => console.log(value, items)}
                />
                <FormItem type='UploadFile' label='上传文件' name='files' required clearable joinValues={false} />
                <FormItem type='UploadFile' listType='text' label='上传文件' name='files1' required clearable />
                <FormItem type='Component' label='Component-自定义' name='email' placeholder='请选择' required>
                  <View>
                    自定义Input
                    <Input onInput={handleChange('email') as any} placeholder='请输入' value={values.email} />
                  </View>
                </FormItem>
                <View
                  onTouchStart={e => {
                    console.warn('onTouchStart', e.touches[0]);
                  }}>
                  6666666
                </View>
                <Button
                  type='primary'
                  style={{ marginTop: 12 }}
                  onClick={() => {
                    if (!isValid) {
                      Taro.showToast({ icon: 'none', title: flatFormikErrors(errors)[0] });
                      return;
                    }
                    submitForm();
                  }}>
                  提交
                </Button>
              </View>
            );
          }}
        </Form>
      </ScrollView>
    </TopView>
  );
};
export default FormPage;
